package com.cardbaobao.cardbabyclient.ui.activity;

import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.buried.Google;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.buried.SelfUtils;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.utils.DensityUtil;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.widget.TitleBar;
import com.cardbaobao.cardbabyclient.widget.pulltorefresh.XListView;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.titles.SimplePagerTitleView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import rx.Observable;
import rx.Subscriber;

/**
 * Created by Jiangzx on 11:23.
 * 公积金查询结果
 */
public class ProvidentFundResultActivity extends BaseActivity implements XListView.IXListViewListener {
    @BindView(R.id.title_bar)
    TitleBar titleBar;

    @BindView(R.id.magic_indicator)
    MagicIndicator indicator;

    @BindView(R.id.view_pager)
    ViewPager viewPager;

    ListView baseInfoListView;
    XListView detailListView;
    ArrayList<View> views;

    private String taskId;
    private int page = 1;
    private String channelType;

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);

        channelType = getIntent().getStringExtra(InquiriesActivity.CHANNEL_TYPE_S);
        mCurrentPageId= Self.Page.app_provident_fund_inquiry_success_page;

        initIntent();
        titleBar.setLeftViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        titleBar.setRightBtClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SelfUtils.buriedClickData(Self.Action.app_click_provident_fund_inquiry_switch_account,
                        Self.Action.app_click_provident_fund_inquiry_switch_account_des,
                        mEnterPageTime,
                        mCurrentPageId,
                        mPrePageId);

                mIntent.setClass(mContext, InquiriesActivity.class);
                mIntent.putExtra(InquiriesActivity.CHANNEL_TYPE_S,
                        InquiriesActivity.CHANNEL_GJJ);
                startActivity(mIntent);
                finish();
            }
        });
        configViewPager();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_provident_fund_result;
    }

    private void configViewPager() {
        CommonNavigator commonNavigator = new CommonNavigator(mContext);
        commonNavigator.setAdjustMode(true);
        commonNavigator.setAdapter(new CommonNavigatorAdapter() {
            @Override
            public int getCount() {
                return 2;
            }

            @Override
            public IPagerTitleView getTitleView(Context context, final int index) {
                SimplePagerTitleView titleView = new SimplePagerTitleView(context);
                titleView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 16.0f);
                titleView.setSelectedColor(0xff333333);
                titleView.setNormalColor(0xff999999);
                titleView.setGravity(Gravity.CENTER);
                if (index == 0) {
                    titleView.setText("缴存信息");
                } else {
                    titleView.setText("缴存明细");
                }
                titleView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        viewPager.setCurrentItem(index);
                    }
                });
                return titleView;
            }

            @Override
            public IPagerIndicator getIndicator(Context context) {
//                LinePagerIndicator indicator=new LinePagerIndicator(context);
//                indicator.setMode(LinePagerIndicator.MODE_MATCH_EDGE);
//                indicator.setLineHeight(DensityUtil.dp2px(context,2.0f));
//                indicator.setColors(0xff5facff);
                return null;
            }
        });
        indicator.setNavigator(commonNavigator);

        views = new ArrayList<>();
        baseInfoListView = new ListView(mContext);
        ViewGroup.LayoutParams params =
                new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT);
        baseInfoListView.setLayoutParams(params);
        baseInfoListView.setDividerHeight(0);
        baseInfoListView.setVerticalScrollBarEnabled(false);

        detailListView = new XListView(mContext);
        detailListView.setVerticalScrollBarEnabled(false);
        detailListView.setLayoutParams(params);
        detailListView.setDividerHeight(0);
        detailListView.setBackgroundResource(R.drawable.shape_corner_6dp_solid_fff);
        detailListView.setPadding(0, DensityUtil.dp2px(6), 0, DensityUtil.dp2px(6));
        detailListView.setPullRefreshEnable(true);
        detailListView.setPullLoadEnable(true);
        detailListView.setXListViewListener(this);

        views.add(baseInfoListView);
        views.add(detailListView);
        viewPager.setAdapter(new ProvidentFundAdapter());
        ViewPagerHelper.bind(indicator, viewPager);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (baseInfoListView.getAdapter() == null) {
            loadBaseInfo();
        }
        if (InquiriesActivity.CHANNEL_GJJ.equals(channelType)) {
            GoogleAnalyticsUtil.setScreenName(Google.ACCUM_FUND_QUERY_SUC);
        } else {
            GoogleAnalyticsUtil.setScreenName(Google.SOCIAL_QUERY_SUC);
        }

    }

    @Override
    public void onRefresh() {
        if (TextUtils.isEmpty(taskId)) {
            detailListView.stopRefresh();
        } else {
            page = 1;
            loadDetailInfo(taskId, page);
        }
    }

    @Override
    public void onLoadMore() {
        if (TextUtils.isEmpty(taskId)) {
            detailListView.stopLoadMore();
        } else {
            page++;
            if (page < 1) {
                page = 1;
            }
            loadDetailInfo(taskId, page);
        }
    }

    private class ProvidentFundAdapter extends PagerAdapter {
        @Override
        public int getCount() {
            return views == null ? 0 : views.size();
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View view = null;
            if (views != null && views.size() > 0) {
                view = views.get(position);
                container.addView(view);
            }
            return view;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            if (views != null && views.size() > 0) {
                View view = views.get(position);
                container.removeView(view);
            }
        }

        @Override
        public int getItemPosition(Object object) {
            return PagerAdapter.POSITION_NONE;
        }
    }

    private void loadBaseInfo() {
        showProgressDialog(false);
        Observable<String> observable=
                Api.getPersonProvidentFundBase(mApplication.getUser().getID());
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                dismissProgressDialog();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_data_fail));
            }

            @Override
            public void onNext(String s) {
                dismissProgressDialog();
                JSONObject json=JSON.parseObject(s).getJSONObject("baseInfo");
                if (json != null) {
                    taskId = json.getString("task_id");
                    loadDetailInfo(taskId, 1);
                    List<BaseBean> data = new ArrayList<>();
                    data.add(new BaseBean(FundBaseAdapter.TYPE_CONTENT_TOP,
                            "姓名:", json.getString("name")));
                    //小分割线
                    data.add(new BaseBean(FundBaseAdapter.TYPE_DIVIDER_MINI, "", ""));
                    data.add(
                            new BaseBean(FundBaseAdapter.TYPE_CONTENT_NORMAL,
                                    "公积金账号:", json.getString("cust_no")));
                    //小分割线
                    data.add(new BaseBean(FundBaseAdapter.TYPE_DIVIDER_MINI, "", ""));
                    data.add(
                            new BaseBean(FundBaseAdapter.TYPE_CONTENT_BOTTOM,
                                    "单位名称:", json.getString("corp_name")));
                    //大分割线
                    data.add(new BaseBean(FundBaseAdapter.TYPE_DIVIDER_MAX, "", ""));

                    int balance = json.getIntValue("balance");
                    if (balance % 100 == 0) {
                        data.add(
                                new BaseBean(FundBaseAdapter.TYPE_CONTENT_TOP,
                                        "账号余额:", balance / 100 + "元"));
                    } else {
                        data.add(
                                new BaseBean(FundBaseAdapter.TYPE_CONTENT_TOP,
                                        "账号余额:", balance / 100.0f + "元"));
                    }
                    //小分割线
                    data.add(new BaseBean(FundBaseAdapter.TYPE_DIVIDER_MINI, "", ""));
                    data.add(new BaseBean(FundBaseAdapter.TYPE_CONTENT_NORMAL,
                            "账号状态:", json.getString("pay_status_desc")));
                    //小分割线
                    data.add(new BaseBean(FundBaseAdapter.TYPE_DIVIDER_MINI, "", ""));
                    int base = json.getIntValue("base_number");
                    if (base % 100 == 0) {
                        data.add(
                                new BaseBean(FundBaseAdapter.TYPE_CONTENT_BOTTOM,
                                        "缴存基数:", base / 100 + "元"));
                    } else {
                        data.add(
                                new BaseBean(FundBaseAdapter.TYPE_CONTENT_BOTTOM,
                                        "缴存基数:", base / 100.0f + "元"));
                    }
                    //大分割线
                    data.add(new BaseBean(FundBaseAdapter.TYPE_DIVIDER_MAX, "", ""));
                    data.add(
                            new BaseBean(FundBaseAdapter.TYPE_CONTENT_TOP,
                                    "单位缴存比例:",
                                    json.getIntValue("monthly_corp_proportion") + "%"));
                    int companyPay = json.getIntValue("monthly_corp_income");
                    if (companyPay == 0) {
                        //计算公司缴存金额
                        companyPay = base * json.getIntValue("monthly_corp_proportion") / 100;
                    }
                    //小分割线
                    data.add(new BaseBean(FundBaseAdapter.TYPE_DIVIDER_MINI, "", ""));
                    if (companyPay % 100 == 0) {
                        data.add(
                                new BaseBean(FundBaseAdapter.TYPE_CONTENT_NORMAL,
                                        "月缴存额单位部分:", companyPay / 100 + "元"));
                    } else {
                        data.add(
                                new BaseBean(FundBaseAdapter.TYPE_CONTENT_NORMAL,
                                        "月缴存额单位部分:", companyPay / 100.0f + "元"));
                    }
                    //小分割线
                    data.add(new BaseBean(FundBaseAdapter.TYPE_DIVIDER_MINI, "", ""));
                    data.add(
                            new BaseBean(FundBaseAdapter.TYPE_CONTENT_NORMAL,
                                    "个人缴存比例:",
                                    json.getIntValue("monthly_cust_proportion") + "%"));
                    int personalPay = json.getIntValue("monthly_cust_income");
                    if (personalPay == 0) {
                        //计算个人缴存金额
                        personalPay = base * json.getIntValue("monthly_cust_proportion") / 100;
                    }
                    //小分割线
                    data.add(new BaseBean(FundBaseAdapter.TYPE_DIVIDER_MINI, "", ""));
                    if (personalPay % 100 == 0) {
                        data.add(
                                new BaseBean(FundBaseAdapter.TYPE_CONTENT_BOTTOM,
                                        "月缴存额个人部分:", personalPay / 100 + "元"));
                    } else {
                        data.add(
                                new BaseBean(FundBaseAdapter.TYPE_CONTENT_BOTTOM,
                                        "月缴存额个人部分:", personalPay / 100.0f + "元"));
                    }
                    baseInfoListView.setAdapter(new FundBaseAdapter(data));
                } else {
                    initIntent();
                    mIntent.setClass(mContext, InquireNoDataActivity.class);
                    mIntent.putExtra(InquireNoDataActivity.TITLE_TEXT, "公积金查询");
                    mIntent.putExtra(InquiriesActivity.CHANNEL_TYPE_S,
                            InquiriesActivity.CHANNEL_GJJ);
                    startActivity(mIntent);
                    finish();
                }
            }
        });
    }

    private FundDetailAdapter detailInfoAdapter;

    private class DetailInfo {
        private int type=FundDetailAdapter.TYPE_CONTENT;
        private String text;
        private String date;
        private String amount;
    }

    private class FundBaseAdapter extends BaseAdapter {
        private static final int TYPE_DIVIDER_MINI = 1;
        private static final int TYPE_DIVIDER_MAX = 2;
        private static final int TYPE_CONTENT_NORMAL = 3;
        private static final int TYPE_CONTENT_TOP = 4;
        private static final int TYPE_CONTENT_BOTTOM = 5;

        private int radian;
        private GradientDrawable topBgDrawable;
        private GradientDrawable bottomBgDrawable;
        private Drawable normalBgDrawable;

        private List<BaseBean> data;

        FundBaseAdapter(List<BaseBean> data) {
            this.data = data;
            this.radian = DensityUtil.dp2px(6);
            this.topBgDrawable = new GradientDrawable(GradientDrawable.Orientation.TL_BR, new int[]{0xffffffff, 0xffffffff});
            this.topBgDrawable.setCornerRadii(new float[]{radian, radian, radian, radian, 0, 0, 0, 0});
            this.bottomBgDrawable = new GradientDrawable(GradientDrawable.Orientation.TL_BR, new int[]{0xffffffff, 0xffffffff});
            this.bottomBgDrawable.setCornerRadii(new float[]{0, 0, 0, 0, radian, radian, radian, radian});
            this.normalBgDrawable = new ColorDrawable(0xffffffff);
        }

        @Override
        public int getCount() {
            return data == null ? 0 : data.size();
        }

        @Override
        public int getItemViewType(int position) {
            return data == null ? super.getItemViewType(position) : data.get(position).type;
        }

        @Override
        public Object getItem(int position) {
            return data == null ? null : data.get(position);
        }

        @Override
        public long getItemId(int position) {
            return data == null ? 0 : data.get(position).type;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Holder holder;
            int viewType = getItemViewType(position);
            if (convertView == null) {
                if (viewType == TYPE_DIVIDER_MINI) {
                    ImageView dividerMini = new ImageView(mContext);
                    dividerMini.setLayoutParams(new AbsListView.LayoutParams(
                            AbsListView.LayoutParams.MATCH_PARENT,1));
                    dividerMini.setImageDrawable(new ColorDrawable(Constant.DIVIDER_COLOR));
                    convertView = dividerMini;
                } else if (viewType == TYPE_DIVIDER_MAX) {
                    View dividerMini = new View(mContext);
                    dividerMini.setLayoutParams(new AbsListView.LayoutParams(
                            AbsListView.LayoutParams.MATCH_PARENT,DensityUtil.dp2px(12)));
                    dividerMini.setBackgroundColor(0xfff2f2f2);
                    convertView = dividerMini;
                } else {
                    View view = LayoutInflater.from(mContext).inflate(R.layout.item_tv_l_r, parent, false);
                    holder = new Holder();
                    holder.left = (TextView) view.findViewById(R.id.tv_left);
                    holder.right = (TextView) view.findViewById(R.id.tv_right);
                    view.setTag(R.layout.item_tv_l_r, holder);
                    convertView = view;
                }
            }
            BaseBean baseBean = data.get(position);
            if (viewType == TYPE_CONTENT_BOTTOM || viewType == TYPE_CONTENT_TOP || viewType == TYPE_CONTENT_NORMAL) {
                holder = (Holder) convertView.getTag(R.layout.item_tv_l_r);
                holder.left.setText(baseBean.textLeft);
                holder.right.setText(baseBean.textRight);
                switch (viewType) {
                    case TYPE_CONTENT_TOP:
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                            convertView.setBackground(topBgDrawable);
                        } else {
                            convertView.setBackgroundDrawable(topBgDrawable);
                        }
                        break;
                    case TYPE_CONTENT_BOTTOM:
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                            convertView.setBackground(bottomBgDrawable);
                        } else {
                            convertView.setBackgroundDrawable(bottomBgDrawable);
                        }
                        break;
                    case TYPE_CONTENT_NORMAL:
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                            convertView.setBackground(normalBgDrawable);
                        } else {
                            convertView.setBackgroundDrawable(normalBgDrawable);
                        }
                        break;
                }
            }
            return convertView;
        }

        private class Holder {
            TextView left;
            TextView right;
        }
    }

    private class BaseBean {
        int type;
        String textLeft;
        String textRight;

        BaseBean(int type, String textLeft, String textRight) {
            this.type = type;
            this.textLeft = textLeft;
            this.textRight = textRight;
        }
    }

    private class FundDetailAdapter extends BaseAdapter {
        private static final int TYPE_DIVIDER=1;
        private static final int TYPE_CONTENT=2;
        @Override
        public int getCount() {
            return detailInfoList == null ? 0 : detailInfoList.size();
        }

        @Override
        public Object getItem(int position) {
            return detailInfoList == null ? null : detailInfoList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            int viewType=getItemViewType(position);
            if(viewType==TYPE_CONTENT){
                Holder holder;
                if (convertView == null) {
                    holder = new Holder();
                    convertView = LayoutInflater.from(mContext).inflate(R.layout.item_provident_fund_detail, parent, false);
                    holder.tvText = (TextView) convertView.findViewById(R.id.tv_description);
                    holder.tvDate = (TextView) convertView.findViewById(R.id.tv_date);
                    holder.tvAmount = (TextView) convertView.findViewById(R.id.tv_amount);
                    convertView.setTag(R.layout.item_provident_fund_detail, holder);
                } else {
                    holder = (Holder) convertView.getTag(R.layout.item_provident_fund_detail);
                }
                DetailInfo info = detailInfoList.get(position);
                holder.tvText.setText(info.text);
                holder.tvDate.setText(info.date);
                holder.tvAmount.setText(info.amount);
            }else{
                if(convertView==null){
                    ImageView view=new ImageView(mContext);
                    view.setLayoutParams(new AbsListView.LayoutParams(AbsListView.LayoutParams.MATCH_PARENT,1));
                    view.setImageDrawable(new ColorDrawable(Constant.DIVIDER_COLOR));
                    convertView=view;
                }
            }
            return convertView;
        }

        @Override
        public int getItemViewType(int position) {
            return detailInfoList.get(position).type;
        }

        @Override
        public int getViewTypeCount() {
            return TYPE_DIVIDER+TYPE_CONTENT;
        }

        class Holder {
            TextView tvText;
            TextView tvDate;
            TextView tvAmount;
        }
    }

    private List<DetailInfo> detailInfoList = new ArrayList<>();

    private void loadDetailInfo(String taskId, final int page) {
        showProgressDialog(false);
        Observable<String> observable=
                Api.getPersonProvidentFundDetail(taskId,page,20);
        observable.subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                ProvidentFundResultActivity.this.page--;
                dismissProgressDialog();
                ToastUtil.showToast(ApplicationHelper.
                        getApplicationContext().
                        getString(R.string.string_request_data_fail));
                detailListView.stopRefresh();
                detailListView.stopLoadMore();
            }

            @Override
            public void onNext(String s) {
                dismissProgressDialog();
                JSONObject json = JSON.parseObject(s);
                JSONArray array = json.getJSONArray("billList");
                if (array != null && array.size() > 0) {
                    if (page == 1) {
                        detailInfoList.clear();
                    }
                    JSONObject object;
                    DetailInfo info;
                    DetailInfo dividerInfo=new DetailInfo();
                    dividerInfo.type=FundDetailAdapter.TYPE_DIVIDER;
                    for (int i = 0, size = array.size(); i < size; i++) {
                        object = array.getJSONObject(i);
                        info = new DetailInfo();
                        info.text = object.getString("desc");
                        info.date = object.getString("deal_time");
                        int balance = object.getIntValue("balance");
                        int income = object.getIntValue("income");
                        if (balance < income) {
                            //支出
                            if (income % 100 == 0) {
                                info.amount = "-" + income / 100 + "元";
                            } else {
                                info.amount = "-" + income / 100.0f + "元";
                            }
                        } else {
                            //收入
                            if (income % 100 == 0) {
                                info.amount = "+" + income / 100 + "元";
                            } else {
                                info.amount = "+" + income / 100.0f + "元";
                            }
                        }
                        detailInfoList.add(info);
                        if(i<size-1){
                            detailInfoList.add(dividerInfo);
                        }
                    }
                    int size = json.getIntValue("size");
                    if (detailInfoList.size() < size) {
                        //启用加载更多
                        detailListView.setPullLoadEnable(true);
                    } else {
                        //禁用加载更多
                        detailListView.setPullLoadEnable(false);
                    }
                    if (detailInfoAdapter == null) {
                        detailInfoAdapter = new FundDetailAdapter();
                        detailListView.setAdapter(detailInfoAdapter);
                    }
                    detailInfoAdapter.notifyDataSetChanged();
                } else {
                    ToastUtil.showToast("暂时没有查询到数据");
                }
            }
        });
    }
}
